package cn.antblog.spring.ReflectionUtils.doWithFields;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaoxu
 * @date 2022-02-14 22:26
 * mybatis_learn:com.xiaoxu.dto.PreciousFruit
 */
public class PreciousFruit {
    @MFruit(name = "芒果", num = 1)
    private String fruitOne;

    @MFruit(name = "猕猴桃", num = 2)
    private String fruitTwo;

    @MFruit(name = "香蕉", num = 3)
    public String fruitThree;

    @MFruit(name = "砂糖橘", num = 4)
    protected String fruitFour;

    public static Map<Long, Field> injectMethod() {
        Map<Long, Field> m = new HashMap<>();
        ReflectionUtils.doWithFields(PreciousFruit.class,
                // FieldCallback是一个函数式接口，所以可以使用lambda表达式,
                // 也可以使用方法引用，或者直接new 重写接口的doWith方法
                new ReflectionUtils.FieldCallback() {
                    @Override
                    public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                        System.out.println("我是回调，哈哈哈哈");
                        if (field.isAnnotationPresent(MFruit.class)) {
                            System.out.printf("字段:%s;具有注解MFruit%n", field);
                            long number = field.getAnnotation(MFruit.class).num();
                            if (m.put(number, field) != null) {
                                System.out.println("该水果number重复，跳过");
                            }
                        }
                        System.out.println("********");
                    }
                });
        return m;
    }

    public static void main(String[] args) {
        Map<Long, Field> longFieldMap = PreciousFruit.injectMethod();
        longFieldMap.forEach((k, v) -> System.out.printf("map的key:%s,value:%s%n", k, v));
    }
}
